package com.astrob.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;

/**
 * 从文件中读取对象数据
 * */

public class ReadObjectsFromFile<T> {

	private ArrayList<T> m_objectsList = null;

	public ReadObjectsFromFile() {
		m_objectsList = null;
	}

	/**
	 * Read objects from file
	 * 
	 * @param szFilePath
	 *            [in] file path
	 * @return T[][out] objects array
	 * */

	@SuppressWarnings("unchecked")
	public final T[] onReadObjectsBuffer(final String szFilePath) {
		m_objectsList = new ArrayList<T>();
		onReadObjectsList(szFilePath, m_objectsList);
		return (T[]) m_objectsList.toArray();
	}

	/**
	 * Read objects from file
	 * 
	 * @param szFilePath
	 *            [in] file path
	 * @return ArrayList<T>[out] objects list
	 * */
	public final ArrayList<T> onReadObjectsList(final String szFilePath) {
		m_objectsList = new ArrayList<T>();
		onReadObjectsList(szFilePath, m_objectsList);
		return m_objectsList;
	}

	/**
	 * Read objects from file
	 * 
	 * @param szFilePath
	 *            [in] file path
	 * @param objsList
	 *            [out] objects list
	 * @return void
	 * */

	@SuppressWarnings("unchecked")
	public void onReadObjectsList(final String szFilePath, ArrayList<T> objsList) {
		if (null == szFilePath || null == objsList)
			return;
		File file = new File(szFilePath);
		if (null == file || file.exists() == false)
			return;

		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			ObjectInputStream objInputStream = new ObjectInputStream(
					fileInputStream);

			while (fileInputStream.available() > 0)
				objsList.add((T) objInputStream.readObject());

			objInputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (StreamCorruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
	}
}
